"""
商品购买业务处理模块
"""
import json
import time
import random
from datetime import datetime
from typing import Dict, List, Callable, Any
from functools import wraps
import random

from com.db.order_record_manager import OrderRecordManager
from reqapi.batch_sell_api import BatchSellOrderApi, BatchSellOrderRequest, CommodityItem
from reqapi.query_batch_order import QueryBatchOrderApi
from reqapi.payment_confirm import PaymentConfirmApi
from reqapi.payment_query_list import PaymentQueryListApi
from reqapi.payment_status import PaymentStatusApi
from biz.offer_commodity import OfferCommodity
from com.utils.logger import get_logger, MODULE_SCAN
from com.db.order_account_manager import OrderAccountManager

# 创建logger实例
logger = get_logger(module=MODULE_SCAN)

def retry_on_failure(max_retries: int = 3, retry_delay: float = 1.0, 
                    retryable_exceptions: tuple = (Exception,)) -> Callable:
    """
    重试装饰器
    Args:
        max_retries: 最大重试次数
        retry_delay: 重试间隔（秒）
        retryable_exceptions: 需要重试的异常类型
    """
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args, **kwargs) -> Any:
            last_exception = None
            for attempt in range(max_retries):
                try:
                    result = func(*args, **kwargs)
                    # 检查返回结果是否表示失败
                    if isinstance(result, dict) and not result.get("success"):
                        if attempt == max_retries - 1:
                            return result
                        logger.info(f"[重试] {func.__name__} 返回失败，第 {attempt + 1} 次重试")
                        time.sleep(retry_delay)
                        continue
                    return result
                except retryable_exceptions as e:
                    last_exception = e
                    if attempt == max_retries - 1:
                        logger.warning(f"[重试] {func.__name__} 达到最大重试次数")
                        break
                    logger.info(f"[重试] {func.__name__} 发生异常，第 {attempt + 1} 次重试: {str(e)}")
                    time.sleep(retry_delay)
            
            # 所有重试都失败了
            error_msg = f"{func.__name__} 失败，重试 {max_retries} 次后仍然失败: {str(last_exception)}"
            logger.error(error_msg)
            return {"success": False, "message": error_msg}
        return wrapper
    return decorator

class PurchaseCommodity:
    def __init__(self, order_account=None, task=None, script=None):
        """
        初始化购买商品处理类
        Args:
            order_account: 购买账号信息，格式如 {
                "device_id": "xxx",
                "device_token": "xxx",
                "auth_token": "Bearer xxx",
                "uk": "xxx"
            }
            task: 任务信息
            script: 脚本信息
        """
        self.task = task
        self.script = script
        self.order_manager = OrderRecordManager()
        
        # 如果直接传递了order_account，则使用传递的账号信息
        if order_account:
            self.device_token = order_account.get("device_id", "")
            self.device_id = order_account.get("device_id", "")
            self.auth_token = order_account.get("uu_token", "")
            self.uk = order_account.get("uk", "")
            self.order_account = order_account
        # 如果没有传递order_account，但有脚本信息，则尝试通过脚本获取关联的下单账号
        elif script:
            # 获取order_account_id，兼容字典和对象两种情况
            order_account_id = script.get("order_account_id") if isinstance(script, dict) else getattr(script, "order_account_id", None)
            
            if order_account_id:
                logger.info(f"通过脚本关联的下单账号ID {order_account_id} 获取账号信息")
                from com.db.order_account_manager import OrderAccountManager
                account_manager = OrderAccountManager()
                account = account_manager.get_account_by_id(order_account_id)
                
                if account:
                    self.device_token = account.get("device_id", "")
                    self.device_id = account.get("device_id", "")
                    self.auth_token = account.get("uu_token", "")
                    self.uk = account.get("uk", "")
                    self.order_account = account
                    logger.info(f"成功获取到脚本关联的下单账号信息")
                else:
                    logger.error(f"无法获取脚本关联的下单账号ID {order_account_id} 的信息")
                    self.device_token = ""
                    self.device_id = ""
                    self.auth_token = ""
                    self.uk = ""
                    self.order_account = None
        else:
            # 如果既没有传递order_account，也没有脚本关联的账号，则初始化为空
            logger.warning("未提供下单账号信息，也无法从脚本获取关联账号")
            self.device_token = ""
            self.device_id = ""
            self.auth_token = ""
            self.uk = ""
            self.order_account = None

    def _validate_purchase_params(self, template_id: str, commodity_list: List[Dict], pay_sell_amount: float, unit_price: float) -> Dict:
        """
        验证购买参数
        Args:
            template_id: 饰品id
            commodity_list: 商品列表
            pay_sell_amount: 总金额
            unit_price: 单价
        Returns:
            Dict: 验证结果，格式为 {"valid": bool, "message": str}
        """
        if not template_id or not isinstance(template_id, str):
            return {"valid": False, "message": "无效的模板ID"}
            
        if not commodity_list or not isinstance(commodity_list, list):
            return {"valid": False, "message": "无效的商品列表"}
            
        if not all(isinstance(item, dict) for item in commodity_list):
            return {"valid": False, "message": "商品列表格式错误"}
            
        required_keys = {"commodityId", "commodityIdPrice", "templateId"}
        for item in commodity_list:
            missing_keys = required_keys - set(item.keys())
            if missing_keys:
                return {"valid": False, "message": f"商品缺少必要字段: {', '.join(missing_keys)}"}
                
            if not isinstance(item.get("commodityId"), (int, str)):
                return {"valid": False, "message": "商品ID格式错误"}
                
            try:
                price = float(item.get("commodityIdPrice", 0))
                if price <= 0:
                    return {"valid": False, "message": "商品价格必须大于0"}
            except (ValueError, TypeError):
                return {"valid": False, "message": "商品价格格式错误"}
                
            if str(item.get("templateId")) != str(template_id):
                return {"valid": False, "message": "商品模板ID不匹配"}
        
        try:
            if float(pay_sell_amount) <= 0:
                return {"valid": False, "message": "总金额必须大于0"}
        except (ValueError, TypeError):
            return {"valid": False, "message": "总金额格式错误"}
            
        try:
            if float(unit_price) <= 0:
                return {"valid": False, "message": "单价必须大于0"}
        except (ValueError, TypeError):
            return {"valid": False, "message": "单价格式错误"}
            
        # 验证总金额与商品价格总和是否匹配
        total_price = sum(float(item.get("commodityIdPrice", 0)) for item in commodity_list)
        if abs(total_price - float(pay_sell_amount)) > 0.01:  # 允许0.01的误差
            return {"valid": False, "message": f"总金额({pay_sell_amount})与商品价格总和({total_price})不匹配"}
            
        return {"valid": True, "message": "验证通过"}

    def process_purchase(self, template_id: str, commodity_list: List[Dict], pay_sell_amount: float, unit_price: float) -> Dict:
        """
        处理购买请求
        Args:
            template_id: 饰品id
            commodity_list: 商品列表，格式如 [{"commodityId":1072672642,"commodityIdPrice":"12","templateId":109757}]
            pay_sell_amount: 总金额
            unit_price: 单价
        Returns:
            Dict: 处理结果
        """
        try:
            # 参数验证
            validation_result = self._validate_purchase_params(template_id, commodity_list, pay_sell_amount, unit_price)
            if not validation_result["valid"]:
                return {"success": False, "message": validation_result["message"]}

            # 1. 创建批量订单
            logger.info(f"开始创建订单，模板ID: {template_id}, 商品数量: {len(commodity_list)}")
            order_result = self._create_batch_order(template_id, commodity_list, pay_sell_amount, unit_price)
            logger.info(f"创建批量订单结果: {order_result}")
            if not order_result["success"]:
                return order_result

            order_info = order_result["data"]["orderInfo"]
            order_no = order_info["orderNo"]
            pay_order_no = order_info["payOrderNo"]
            wait_payment_data_no = order_info["waitPaymentDataNo"]

            # 为每个商品创建订单记录
            logger.debug(f"商品列表: {commodity_list}")
            record_ids = []
            for item in commodity_list:
                commodity = item.get('commodity', {})
                record_data = {
                    'account_id': self.order_account.get('id'),
                    'account_name': self.order_account.get('name'),
                    'script_id': self.script.get('id') if self.script else None,
                    'script_name': self.script.get('name') if self.script else None,
                    'task_id': self.task.get('id') if self.task else None,
                    'task_name': self.task.get('name') if self.task else None,
                    'order_no': order_no,
                    'pay_order_no': pay_order_no,
                    'wait_payment_data_no': wait_payment_data_no,
                    'assetid': commodity.get('Id'),  # Steam资产ID
                    'name': commodity.get('CommodityName'),  # 商品名称
                    'price': float(commodity.get('Price', 0)),  # 价格
                    'game': str(commodity.get('GameId')),  # 游戏ID
                    'goods_id': int(commodity.get('TemplateId', 0)),  # 商品模板ID
                    'market_hash_name': commodity.get('CommodityHashName'),  # 市场哈希名称
                    'paintwear': float(commodity.get('Abrade', 0)),  # 磨损度
                    'expect_income': None,  # 预期收入，暂时为空
                    'buy_status': 1,  # 初始购买状态
                    'pay_type': 7,  # 支付类型
                    'offer_status': 1,  # 初始报价状态
                    'offer_times': 0,  # 报价次数
                    'offer_fail_desc': None,  # 报价失败描述
                    'create_at': datetime.now(),  # 创建时间
                    'update_at': datetime.now(),  # 更新时间
                    'buy_at': None,  # 购买时间
                    'offer_at': None  # 报价时间
                }
                record_id = self.order_manager.add_record(record_data)
                record_ids.append(record_id)


            # 2. 查询支付方式列表
            logger.info(f"开始查询支付方式，订单号: {order_no}")
            payment_list = self._query_payment_list(order_no, wait_payment_data_no, pay_sell_amount)
            logger.info(f"查询支付方式结果: {payment_list}")
            if not payment_list["success"]:
                return payment_list
                
            # 检查余额是否充足
            if payment_list.get("data", {}).get("payList"):
                pay_amount = float(payment_list["data"]["amount"])
                for pay_method in payment_list["data"]["payList"]:
                    if pay_method.get("checked") == 1:  # 选中的支付方式
                        balance = float(pay_method.get("balance", 0))
                        if balance < pay_amount:
                            logger.warning(f"余额不足，订单号: {order_no}, 所需金额: {pay_amount}, 当前余额: {balance}")
                            return {
                                "success": False,
                                "message": pay_method.get("jumpTitle", "余额不足，请充值")
                            }

            # 3. 确认支付
            logger.info(f"开始确认支付，订单号: {order_no}, 支付订单号: {pay_order_no}")
            payment_confirm = self._confirm_payment(order_no, pay_order_no, wait_payment_data_no, pay_sell_amount)
            logger.info(f"确认支付结果: {payment_confirm}")
            if not payment_confirm["success"]:
                return payment_confirm
            

            # 4. 查询支付状态
            logger.info(f"开始查询支付状态，订单号: {order_no}, 支付订单号: {pay_order_no}")
            max_query_times = 5  # 最大查询次数
            last_error_message = "未知错误"  # 记录最后一次错误信息
            
            for query_time in range(max_query_times):
                # 随机等待0.5-3秒
                wait_time = random.uniform(0.5, 3.0)
                time.sleep(wait_time)
                
                logger.info(f"第{query_time + 1}次查询支付状态")
                status_info = self._check_payment_status(order_no, pay_order_no, wait_payment_data_no)
                logger.info(f"查询支付状态结果: {status_info}")
                
                if not status_info["success"]:
                    logger.error(f"查询支付状态失败: {status_info['message']}")
                    last_error_message = status_info["message"]
                    if query_time == max_query_times - 1:  # 最后一次查询仍然失败
                        logger.warning(f"查询支付状态失败，开始更新订单状态，记录ID列表: {record_ids}")
                        for record_id in record_ids:
                            logger.info(f"更新记录 {record_id} 为支付失败状态")
                            self.order_manager.update_buy_status(
                                record_id=int(record_id),
                                status=0,  # 0表示支付失败
                                desc=f"查询支付状态失败: {last_error_message}"
                            )
                        logger.info("所有记录更新完成")
                        return {"success": False, "message": f"查询支付状态失败: {last_error_message}"}
                    continue
                    
                # 支付状态查询成功，处理状态
                logger.info(f"开始处理支付状态，状态信息: {status_info}")
                pay_status = status_info["data"]["payStatus"]
                pay_state_msg = status_info["data"].get("payStateMsg", "未知状态")
                logger.info(f"支付状态: {pay_status}, 状态说明: {pay_state_msg}")
                
                # 获取当前时间的ISO格式字符串
                current_time = datetime.now().isoformat()
                
                if pay_status == 2:  # 2表示支付成功
                    logger.info(f"支付成功，开始更新订单状态，记录ID列表: {record_ids}")
                    for record_id in record_ids:
                        logger.info(f"更新记录 {record_id} 为已支付状态")
                        self.order_manager.update_buy_status(
                            record_id=int(record_id),
                            status=2,  # 2表示已支付
                            buy_at=current_time
                        )
                    logger.info("所有记录更新完成")
                    break  # 支付成功，跳出循环
                    
                elif pay_status == 3:  # 3表示支付失败
                    logger.warning(f"支付失败，开始更新订单状态，记录ID列表: {record_ids}")
                    for record_id in record_ids:
                        logger.info(f"更新记录 {record_id} 为支付失败状态")
                        self.order_manager.update_buy_status(
                            record_id=int(record_id),
                            status=0,  # 0表示支付失败
                            desc=pay_state_msg
                        )
                    logger.info("所有记录更新完成")
                    return {"success": False, "message": f"支付失败: {pay_state_msg}"}
                    
                elif pay_status == 1:  # 1表示待支付
                    if query_time == max_query_times - 1:  # 最后一次查询仍然是待支付
                        logger.warning(f"支付超时，开始更新订单状态，记录ID列表: {record_ids}")
                        for record_id in record_ids:
                            logger.info(f"更新记录 {record_id} 为支付失败状态")
                            self.order_manager.update_buy_status(
                                record_id=int(record_id),
                                status=0,  # 0表示支付失败
                                desc="支付超时：查询5次后仍处于待支付状态"
                            )
                        logger.info("所有记录更新完成")
                        return {"success": False, "message": "支付超时：查询5次后仍处于待支付状态"}
                    logger.info(f"等待支付中，{wait_time:.1f}秒后进行下一次查询")
                    continue
                    
                else:  # 其他未知状态
                    logger.warning(f"支付状态未知，开始更新订单状态，记录ID列表: {record_ids}")
                    for record_id in record_ids:
                        logger.info(f"更新记录 {record_id} 为支付失败状态")
                        self.order_manager.update_buy_status(
                            record_id=int(record_id),
                            status=0,  # 0表示支付失败
                            desc=f"未知状态: {pay_state_msg}"
                        )
                    logger.info("所有记录更新完成")
                    return {"success": False, "message": f"支付状态未知: {pay_state_msg}"}

            # 5. 查询批量订单信息
            logger.info(f"开始查询批量订单，订单号: {order_no}")
            # 获取订单列表
            logger.info("开始获取发货订单列表")
            max_retries = 5
            retry_count = 0
            
            while retry_count < max_retries:
                batch_order_info = self._query_batch_order_info(order_no)
                logger.info(f"查询批量订单结果: {batch_order_info}")
                if not batch_order_info["success"]:
                    continue
            
                # 获取发货订单列表
                batch_data = batch_order_info.get("data", {})
                logger.debug(f"第{retry_count + 1}次尝试，批量订单数据: {batch_data}")
                
                # 检查是否有失败订单
                fail_number = batch_data.get("failNumber", 0)
                total_number = batch_data.get("totalNumber", 0)
                
                if fail_number == total_number and total_number > 0:
                    fail_reasons = batch_data.get("failReasons", [])
                    fail_message = f"所有订单均失败: {', '.join(fail_reasons) if fail_reasons else '未知原因'}"
                    logger.warning(fail_message)
                    # 更新所有记录的支付状态为失败
                    logger.warning(f"开始更新订单状态，记录ID列表: {record_ids}")
                    for record_id in record_ids:
                        logger.info(f"更新记录 {record_id} 为支付失败状态")
                        self.order_manager.update_buy_status(
                            record_id=int(record_id),
                            status=0,  # 0表示支付失败
                            desc=fail_message
                        )
                    logger.info("所有记录更新完成")
                    return {"success": False, "message": fail_message}
                
                send_order_no_list = batch_data.get("successList", [])
                logger.info(f"获取到的订单列表: {send_order_no_list}")
                
                if send_order_no_list:
                    break
                    
                retry_count += 1
                if retry_count < max_retries:
                    wait_time = random.uniform(0, 1)
                    logger.info(f"等待 {wait_time:.2f} 秒后重试...")
                    time.sleep(wait_time)
                    continue
                
                logger.warning(f"达到最大重试次数{max_retries}次，获取订单列表失败")
                
                # 更新所有记录的支付状态为失败
                fail_message = f"重试{max_retries}次后仍无法获取发货订单列表"
                logger.warning(f"获取订单列表失败，开始更新订单状态，记录ID列表: {record_ids}")
                for record_id in record_ids:
                    logger.info(f"更新记录 {record_id} 为支付失败状态")
                    self.order_manager.update_buy_status(
                        record_id=int(record_id),
                        status=0,  # 0表示支付失败
                        desc=fail_message
                    )
                logger.info("所有记录更新完成")
                return {"success": False, "message": fail_message}
            
            # 6. 处理报价
            offer_handler = OfferCommodity(
                device_token=self.device_token,
                device_id=self.device_id,
                auth_token=self.auth_token,
                uk=self.uk
            )
            offer_result = offer_handler.process_offer(send_order_no_list, record_ids)
            return offer_result

        except Exception as e:
            logger.error(f"处理购买请求失败: {str(e)}")
            return {"success": False, "message": f"处理购买请求失败: {str(e)}"}

    @retry_on_failure(max_retries=3, retry_delay=1.0)
    def _query_payment_list(self, order_no: str, wait_payment_data_no: str, payment_amount: float) -> Dict:
        """查询支付方式列表"""
        try:
            api = PaymentQueryListApi(
                device_token=self.device_token,
                device_id=self.device_id,
                auth_token=self.auth_token,
                uk=self.uk
            )
            
            result = api.execute(
                user_id=self.order_account["uu_user_id"],
                order_no=order_no, 
                wait_payment_data_no=wait_payment_data_no,
                payment_amount=payment_amount
            )
            logger.debug(f"查询支付方式列表API返回结果: {result}")
            return {"success": True, "data": result}
        except Exception as e:
            error_msg = f"查询支付方式失败: {str(e)}"
            logger.error(error_msg)
            return {"success": False, "message": error_msg}

    @retry_on_failure(max_retries=3, retry_delay=1.0)
    def _confirm_payment(self, order_no: str, pay_order_no: str, wait_payment_data_no: str, pay_sell_amount: float) -> Dict:
        """确认支付"""
        try:
            api = PaymentConfirmApi(
                device_token=self.device_token,
                device_id=self.device_id,
                auth_token=self.auth_token,
                uk=self.uk
            )
            
            result = api.execute(
                order_no=order_no,
                out_trade_no=pay_order_no,  # 外部交易号使用pay_order_no
                wait_payment_data_no=wait_payment_data_no,
                payment_amount=pay_sell_amount,  # 使用订单总金额
            )
            logger.debug(f"确认支付API返回结果: {result}")
            return {"success": True, "data": result}
        except Exception as e:
            error_msg = f"确认支付失败: {str(e)}"
            logger.error(error_msg)
            return {"success": False, "message": error_msg}

    @retry_on_failure(max_retries=5, retry_delay=2.0)  # 支付状态查询使用更多的重试次数和更长的间隔
    def _check_payment_status(self, order_no: str, pay_order_no: str, wait_payment_data_no: str) -> Dict:
        """查询支付状态"""
        try:
            api = PaymentStatusApi(
                device_token=self.device_token,
                device_id=self.device_id,
                auth_token=self.auth_token,
                uk=self.uk
            )
            
            result = api.execute(
                order_no=order_no,
                pay_order_no=pay_order_no,
                wait_payment_data_no=wait_payment_data_no
            )
            logger.debug(f"查询支付状态API返回结果: {result}")
            return {"success": True, "data": result}
        except Exception as e:
            error_msg = f"查询支付状态失败: {str(e)}"
            logger.error(error_msg)
            return {"success": False, "message": error_msg}

    def _get_send_order_no_list(self, order_no: str) -> List[str]:
        """
        获取需要发货的订单列表
        Args:
            order_no: 订单号
        Returns:
            List[str]: 需要发货的订单号列表
        """
        try:
            # 查询批量订单信息
            api = QueryBatchOrderApi(
                device_token=self.device_token,
                device_id=self.device_id,
                auth_token=self.auth_token,
                uk=self.uk
            )
            
            result = api.execute(order_no=order_no)
            logger.info(f"[获取发货订单] 批量订单查询结果: {result}")
            
            if result.get("successList"):
                return [item.get("orderNo") for item in result["successList"] if item.get("orderNo")]
            return [order_no]  # 如果没有成功列表，返回原始订单号
            
        except Exception as e:
            logger.error(f"[获取发货订单] 出现错误: {str(e)}")
            return []

    def _create_batch_order(self, template_id: str, commodity_list: List[Dict], pay_sell_amount: float, unit_price: float) -> Dict:
        """创建批量订单"""
        # 验证参数
        if not template_id or not commodity_list or pay_sell_amount <= 0 or unit_price <= 0:
                return {"success": False, "message": "参数错误"}
        
        # 导入新的BatchSellOrderApi和相关类
        
        # 创建批量订单API实例
        api = BatchSellOrderApi(
            device_token=self.device_token,
            device_id=self.device_id,
            auth_token=self.auth_token,
            uk=self.uk
        )
        
        # 转换商品列表格式
        commodity_items = [
            CommodityItem(
                commodityId=int(item.get('commodityId')),
                commodityIdPrice=str(item.get('commodityIdPrice')),
                templateId=int(template_id)
            ) for item in commodity_list
        ]
        
        # 创建请求对象
        request = BatchSellOrderRequest(
            buyNumber=len(commodity_list),
            commodityList=commodity_items,
            orderSubType=9,
            paySellAmount=str(pay_sell_amount),
            templateId=int(template_id),
            unitPrice=str(unit_price),
            Sessionid=self.device_id
        )
        
        # 调用创建订单API
        result = api.create_batch_order(request)

        # 返回成功结果
        logger.debug(f"批量订单API返回结果: {result}")
        return {
            "success": True,
            "data": {
                "templateId": template_id,
                "commodityCount": len(commodity_list),
                "totalAmount": pay_sell_amount,
                "unitPrice": unit_price,
                "commodities": commodity_list,
                "orderInfo": {
                    "orderNo": result.data.orderNo,
                    "payOrderNo": result.data.payOrderNo,
                    "waitPaymentDataNo": result.data.waitPaymentDataNo,
                    "payErrorCode": result.data.payErrorCode,
                    "payErrorMessage": result.data.payErrorMessage,
                    "payString": result.data.payString,
                    "type": result.data.type,
                    "batchOrderNo": result.data.batchOrderNo,
                    "notifyUrl": result.data.notifyUrl
                }
            }
        }

    def _query_batch_order_info(self, order_no: str) -> Dict:
        """查询批量订单信息"""
        try:
            api = QueryBatchOrderApi(
                device_token=self.device_token,
                device_id=self.device_id,
                auth_token=self.auth_token,
                uk=self.uk
            )
            
            result = api.execute(order_no=order_no)
            logger.debug(f"查询批量订单信息API返回结果: {result}")
            return {"success": True, "data": result}
        except Exception as e:
            error_msg = f"查询批量订单信息失败: {str(e)}"
            logger.error(error_msg)
            return {"success": False, "message": error_msg}

# 使用示例
if __name__ == "__main__":
    # 构造script参数
    script = {
        "id": 1,  # 脚本ID
        "name": "测试脚本",  # 脚本名称
        "order_account_id": 3  # 下单账号ID
    }
    
    # 构造task参数
    task = {
        "id": 1,  # 任务ID
        "name": "测试任务"  # 任务名称
    }
    
    # 构造必需参数
    template_id = "483"  # 饰品id，字符串类型
    
    # 商品列表，每个商品需包含commodityId、commodityIdPrice和templateId
    commodity_list = [
        {
            "commodityId": 1303139730,  # 商品ID
            "commodityIdPrice": "0.11",  # 商品价格，字符串类型
            "templateId": 483  # 模板ID，需要和template_id一致
        }
    ]
    
    pay_sell_amount = 0.11  # 总金额，浮点数类型
    unit_price = 9999999.99  # 单价，浮点数类型

    # 获取脚本关联的下单账号
    order_account = None
    
    
    # 初始化PurchaseCommodity并调用process_purchase方法
    purchase = PurchaseCommodity(task=task, script=script, order_account=order_account)
    result = purchase.process_purchase(
        template_id=template_id,
        commodity_list=commodity_list,
        pay_sell_amount=pay_sell_amount,
        unit_price=unit_price
    )
    
    # 打印处理结果
    logger.info(json.dumps(result, ensure_ascii=False, indent=2))
